var request = require('./request');
var sign = require('./sign.js');
var qs = require('./qs.js');

var domain = 'https://api.fcoin.com/v2/';
var key = wx.getStorageSync('key');

var symbols = function () {
    return request({
        uri: domain + 'public/symbols'
    });
}

// 交易深度
var depth = function (symbol) {
    var level = 'L20';
    var uri = domain + `market/depth/${level}/${symbol}`;
    // console.log(uri)
    return request({
        uri: uri,
    });
}

// 今日摘要
var summary = function () {
    return request({
        uri: 'https://www.fcoin.com/api/common/trading_fees_group'
    });
}

var privateApi = function (resource, method, param) {
    method = method || 'GET';
    param = param || {};
    var timestamp = Date.parse(new Date());
    var headers = {
        'FC-ACCESS-KEY': wx.getStorageSync('key'),
        'FC-ACCESS-SIGNATURE': sign(method, domain, resource, timestamp, param),
        'FC-ACCESS-TIMESTAMP': timestamp
    }
    var uri = domain + resource;
    if (method === 'GET' && param) {
        var querystring = qs(param);
        uri = uri + '?' + querystring;
    }
    return request({
        uri: uri,
        headers: headers,
        method: method,
        param: param,
    });
}

// 获取用户余额
var getUserInfo = function () {
    var resource = 'accounts/balance';
    return privateApi(resource);
}

// 查询订单列表
var getOrders = function (param) {
    var resource = 'orders';
    return privateApi(resource, 'GET', param);
}

// 下单
var order = function (param) {
    // console.log(param)
    var resource = 'orders';
    return privateApi(resource, 'POST', param);
}

// 撤单
var cancelOrder = function (order_id) {
    var resource = `orders/${order_id}/submit-cancel`;
    return privateApi(resource, 'POST');
}

// k线
var kline = function (resolution, symbol) {
    return request({
        uri: domain + `market/candles/${resolution}/${symbol}?limit=20`
    });
}

// 导出模块
module.exports = {
    depth,
    getUserInfo,
    getOrders,
    summary,
    symbols,
    order,
    cancelOrder,
    kline,
    // getServerTimestamp,
    // getOrderDetail,
}